package com.whfc.common.third.dingtalk;


import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.taobao.api.ApiException;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;

/**
 * @author likang
 * @description 钉钉机器人向群里发送消息
 * @date 2020-11-18
 */
public class DingTalkUtil {

    private static final Logger logger = LoggerFactory.getLogger(DingTalkUtil.class);

    private final  static  String DingTalkURL = "https://oapi.dingtalk.com/robot/send?";
    public static void sendTextMessage(String accessToken,String secret,String message) {

        //获取签名
        Long  timestamp  =  System.currentTimeMillis();
        String sign;
        try {
            sign = sign(timestamp,secret);
            //拼接钉钉机器人的群消息链接
            String url = DingTalkURL+"access_token=" +accessToken + "&timestamp="+timestamp + "&sign=" + sign;
            DingTalkClient client  =  new DefaultDingTalkClient(url);
            OapiRobotSendRequest  request  =  new OapiRobotSendRequest();
            OapiRobotSendRequest.Text  text  =  new  OapiRobotSendRequest.Text ();

            //设置消息类型为文本
            request.setMsgtype("text");
            //传入消息文本内容
            text.setContent(message);
            request.setText(text);

            //设置消息通知提醒为全部,@所有人
//            OapiRobotSendRequest.At  at  =  new  OapiRobotSendRequest.At ();
//            at.setIsAtAll (true);
//            request.setAt(at);

            try {
                client.execute(request);
                logger.info("发送消息到钉钉群，url:{},message：{}",url, message);
            } catch (ApiException e) {
                logger.info("发送消息失败");
            }

        } catch (Exception e) {
            logger.info("获取签名失败，message：{}", message);
        }


    }

    //签名计算
    public static String  sign(Long  timestamp ,String secret ) throws Exception {
        String  stringToSign  =  timestamp  +  "\n"  +  secret ;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init ( new SecretKeySpec( secret.getBytes ( "UTF-8"), "HmacSHA256" ));
        byte [] signData  =  mac.doFinal ( stringToSign.getBytes ( "UTF-8" ));
        String  sign  =  URLEncoder.encode ( new  String (Base64.encodeBase64 ( signData )), "UTF-8" );
        return sign;
    }


}
